package com.joe.demo.nio.buffer;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Description 分数读
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class TestScatteringReads {

    public static void main(String[] args) {
        try (FileChannel channel = new RandomAccessFile("words.txt", "r").getChannel()) {
            ByteBuffer buffer1 = ByteBuffer.allocate(3);
            ByteBuffer buffer2 = ByteBuffer.allocate(3);
            ByteBuffer buffer3 = ByteBuffer.allocate(5);

            channel.read(buffer1);
            channel.read(buffer2);
            channel.read(buffer3);

            buffer1.flip();
            buffer2.flip();
            buffer3.flip();

            log.info("第一段: {}", StandardCharsets.UTF_8.decode(buffer1));
            log.info("第二段: {}", StandardCharsets.UTF_8.decode(buffer2));
            log.info("第三段: {}", StandardCharsets.UTF_8.decode(buffer3));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
